﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.SqlClient;
using RooHui.Tool;

namespace RooHui.Infrastructure.Entities.EFContext
{
    public class UpdateContext<T> : ModityContext<T>
    {
        private Context context = null;
        private List<string> set = new List<string>();
        private string setsentence = string.Empty;
        public UpdateContext(Context ctx)
        {
            this.context = ctx;
            this.tableName = typeof(T).Name;
        }

        public UpdateContext<T> Set<TKey>(Expression<Func<T, TKey>> expression, object equal)
        {
            if (expression.Body.NodeType != ExpressionType.MemberAccess)
            {
                throw new Exception("表达式错误");
            }
            string column = expression.Body.ToString().Split('.')[1];
            set.Add(String.Format("{0}={1}", column, BuildValue(equal)));
            return this;
        }

        public override int Excute()
        {
            setsentence = "SET ";
            for (int i = 0, len = set.Count; i < len; i++)
            {
                setsentence += set[i] + ",";
                if (i == len - 1)
                {
                    setsentence = setsentence.Remove(setsentence.Length - 1); //移除最后一个逗号
                }
            }
            string sqlScript = String.Format("UPDATE {0} {1} {2}", tableName, setsentence, wheresentence);
            try
            {
                LogHelper.Write(CommonLogger.Application, LogLevel.Trace, "使用扩展Linq执行Update操作，执行语句：" + sqlScript);
                return context.Database.ExecuteSqlCommand(sqlScript);
            }
            catch (SqlException e)
            {
                LogHelper.Write(CommonLogger.Application, LogLevel.Error, e);
                return 0;
            }
        }
    }
}
